package com.ldq.imooc.basics.io;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

/**
 * @Author : 李道泉
 * @Description : 文件读写demo
 * @Date : 2018/4/4 16:09
 * @Modified by :
 */
public class RafDemo {

    public static void main(String[] args) throws IOException {

        File demo = new File("demo");
        if (!demo.exists()) {
            demo.mkdir();
        }
        File file = new File(demo, "raf.bat");
        if (!file.exists()) {
            file.createNewFile();

        }

        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        System.out.println(raf.getFilePointer());

        raf.write('A');
        System.out.println(raf.getFilePointer());
        raf.write('C');
        System.out.println(raf.getFilePointer());

        int i = 0x7fffffff;
        //write每次只能写一个字节，需写四次
        raf.write(i >>> 24);
        raf.write(i >>> 16);
        raf.write(i >>> 8);
        raf.write(i);
        System.out.println(raf.getFilePointer());

        //直接写int
        raf.writeInt(i);
        System.out.println(raf.getFilePointer());

        String s = "中";
        byte[] gbk = s.getBytes("gbk");
        raf.write(gbk);
        System.out.println(raf.getFilePointer());


        //读文件，指针必须移到头部
        raf.seek(0);
        //一次全部读取
        byte[] buf = new byte[(int) raf.length()];
        raf.read(buf);
        System.out.println(Arrays.toString(buf));

        for (byte b : buf) {
            System.out.print(Integer.toHexString(b & 0xff) + " ");

        }

        String s1 = new String(buf);
        System.out.println(s1);

        raf.close();
    }
}
